import React from 'react';

interface UseStreamdownOptions {
  chunkSize?: number;
  interval?: number;
}

export function useStreamdown(text: string, { chunkSize = 3, interval = 35 }: UseStreamdownOptions = {}) {
  const [rendered, setRendered] = React.useState('');
  const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  React.useEffect(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }

    if (!text) {
      setRendered('');
      return;
    }

    const current = rendered.length <= text.length && text.startsWith(rendered) ? rendered : '';
    setRendered(current);

    const type = (index: number) => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
      if (index >= text.length) {
        setRendered(text);
        return;
      }
      const next = Math.min(index + chunkSize, text.length);
      setRendered(text.slice(0, next));
      timerRef.current = setTimeout(() => type(next), interval);
    };

    type(current.length);

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [text]);

  return rendered;
}

export function useStreamdownStatus(rendered: string, target: string) {
  return React.useMemo(() => ({
    isTyping: rendered.length < target.length,
    isEmpty: !rendered.length
  }), [rendered.length, target.length]);
}
